// 敏感词管理服务
export interface SensitiveWord {
    id: string;
    word: string;
    enabled: boolean;
    createdAt: number;
}

export interface SensitiveWordsConfig {
    enabled: boolean;           // 是否启用敏感词过滤
    replaceMode: boolean;       // true: 替换为星号, false: 完全屏蔽
    replaceChar: string;        // 替换字符
    caseSensitive: boolean;     // 是否区分大小写
}

export const DEFAULT_SENSITIVE_WORDS_CONFIG: SensitiveWordsConfig = {
    enabled: true,
    replaceMode: true,
    replaceChar: '*',
    caseSensitive: false
};

class SensitiveWordsService {
    private readonly STORAGE_KEY = 'sensitiveWords';
    private readonly CONFIG_KEY = 'sensitiveWordsConfig';

    // 默认敏感词列表
    private readonly DEFAULT_WORDS = ['傻子', '神经病'];

    // 获取敏感词列表
    getSensitiveWords(): SensitiveWord[] {
        try {
            const stored = localStorage.getItem(this.STORAGE_KEY);
            if (stored) {
                return JSON.parse(stored);
            }
            // 如果没有存储的数据，返回默认敏感词
            return this.DEFAULT_WORDS.map((word, index) => ({
                id: `default_${index}`,
                word,
                enabled: true,
                createdAt: Date.now()
            }));
        } catch (error) {
            console.error('Failed to load sensitive words:', error);
            return [];
        }
    }

    // 保存敏感词列表
    saveSensitiveWords(words: SensitiveWord[]): void {
        try {
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(words));
        } catch (error) {
            console.error('Failed to save sensitive words:', error);
        }
    }

    // 添加敏感词
    addSensitiveWord(word: string): SensitiveWord {
        const words = this.getSensitiveWords();
        const newWord: SensitiveWord = {
            id: `word_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            word: word.trim(),
            enabled: true,
            createdAt: Date.now()
        };

        // 检查是否已存在
        const exists = words.some(w => w.word === newWord.word);
        if (!exists) {
            words.push(newWord);
            this.saveSensitiveWords(words);
        }

        return newWord;
    }

    // 删除敏感词
    removeSensitiveWord(id: string): void {
        const words = this.getSensitiveWords();
        const filtered = words.filter(w => w.id !== id);
        this.saveSensitiveWords(filtered);
    }

    // 更新敏感词状态
    updateSensitiveWord(id: string, updates: Partial<SensitiveWord>): void {
        const words = this.getSensitiveWords();
        const index = words.findIndex(w => w.id === id);
        if (index !== -1) {
            words[index] = { ...words[index], ...updates };
            this.saveSensitiveWords(words);
        }
    }

    // 获取配置
    getConfig(): SensitiveWordsConfig {
        try {
            const stored = localStorage.getItem(this.CONFIG_KEY);
            if (stored) {
                return { ...DEFAULT_SENSITIVE_WORDS_CONFIG, ...JSON.parse(stored) };
            }
            return DEFAULT_SENSITIVE_WORDS_CONFIG;
        } catch (error) {
            console.error('Failed to load sensitive words config:', error);
            return DEFAULT_SENSITIVE_WORDS_CONFIG;
        }
    }

    // 保存配置
    saveConfig(config: SensitiveWordsConfig): void {
        try {
            localStorage.setItem(this.CONFIG_KEY, JSON.stringify(config));
        } catch (error) {
            console.error('Failed to save sensitive words config:', error);
        }
    }

    // 检测文本是否包含敏感词
    containsSensitiveWords(text: string): { hasSensitive: boolean; matchedWords: string[]; filteredText: string } {
        const config = this.getConfig();
        if (!config.enabled) {
            return { hasSensitive: false, matchedWords: [], filteredText: text };
        }

        const words = this.getSensitiveWords().filter(w => w.enabled);
        const matchedWords: string[] = [];
        let filteredText = text;

        words.forEach(wordObj => {
            const word = wordObj.word;
            const searchText = config.caseSensitive ? text : text.toLowerCase();
            const searchWord = config.caseSensitive ? word : word.toLowerCase();

            if (searchText.includes(searchWord)) {
                matchedWords.push(word);

                if (config.replaceMode) {
                    // 替换为星号
                    const regex = new RegExp(word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), config.caseSensitive ? 'g' : 'gi');
                    filteredText = filteredText.replace(regex, config.replaceChar.repeat(word.length));
                } else {
                    // 完全屏蔽
                    filteredText = '';
                }
            }
        });

        return {
            hasSensitive: matchedWords.length > 0,
            matchedWords,
            filteredText
        };
    }

    // 批量导入敏感词
    importWords(words: string[]): void {
        const existingWords = this.getSensitiveWords();
        const newWords: SensitiveWord[] = [];

        words.forEach(word => {
            const trimmedWord = word.trim();
            if (trimmedWord && !existingWords.some(w => w.word === trimmedWord)) {
                newWords.push({
                    id: `imported_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                    word: trimmedWord,
                    enabled: true,
                    createdAt: Date.now()
                });
            }
        });

        if (newWords.length > 0) {
            this.saveSensitiveWords([...existingWords, ...newWords]);
        }
    }

    // 清空所有敏感词
    clearAllWords(): void {
        this.saveSensitiveWords([]);
    }

    // 导出敏感词
    exportWords(): string {
        const words = this.getSensitiveWords();
        return words.map(w => w.word).join('\n');
    }
}

export const sensitiveWordsService = new SensitiveWordsService();
